package com.yilijk.base.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;

import androidx.core.graphics.drawable.DrawableCompat;

import com.yilijk.base.constants.UserInfo;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class BitmapUtils {

    public static Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

    public static Bitmap mergeBitmapDrug(Bitmap firstBitmap, Bitmap secondBitmap, Bitmap thirdBitmap, String drugName, String wecharContent) {
        if (drugName == null) {
            drugName = "";
        }
        if (wecharContent == null) {
            wecharContent = "";
        }
        Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap.getHeight(), firstBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(firstBitmap, new Matrix(), null);
        //二维码背景图
        if (secondBitmap != null) {
            canvas.drawBitmap(secondBitmap, 178, 128, null);
        }
        if (thirdBitmap != null) {
            canvas.drawBitmap(thirdBitmap, 48, 578, null);
        }


        //添加药品名称
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(32);
        paint.setStrokeWidth(2);
        paint.setColor(Color.BLACK);
        String mytext = "";
        if (drugName != null && drugName.length() > 0) {
            float v = paint.measureText(drugName);
            ALog.i("mergeBitmap2", "mergeBitmap2: " + v);
            if (v > firstBitmap.getWidth() / 2) {
                int subIndex = 0;
                if (secondBitmap == null) {
                    subIndex = paint.breakText(drugName, 0, drugName.length(), true, 400, null);
                } else {
                    subIndex = paint.breakText(drugName, 0, drugName.length(), true, secondBitmap.getWidth() * 14 / 10, null);
                }
                mytext = drugName.substring(0, subIndex - 3) + "...";
            }
        }
        //在图片上动态的添加文字
        if (secondBitmap == null) {
            canvas.drawText(mytext, firstBitmap.getWidth() / 4, 500, paint);
        } else {
            canvas.drawText(mytext, secondBitmap.getWidth() / 2, 500, paint);
        }
        Paint paint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint1.setTextSize(40);
        paint1.setStrokeWidth(10);
        paint1.setColor(Color.BLACK);


        //在图片上动态的添加文字
        canvas.drawText(wecharContent, 254, 680, paint1);

        paint1.setTextSize(24);
        String string = SharedPreferencesUtils.getInstance().getString(UserInfo.userName,"");
        canvas.drawText(string == null ? "" : string, (float) (firstBitmap.getWidth() * 0.82), (float) (firstBitmap.getWidth() * 0.11), paint1);
        return bitmap;
    }

    //图片缩放
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int height;
        int width;
        try {
            width = bm.getWidth();
            height = bm.getHeight();
        } catch (Exception e) {
            return bm;
        }

        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);

        return newbm;
    }

    //图片圆角
    public static Bitmap makeRoundCorner(Bitmap bitmap, int px) {
        int height;
        int width;
        try {
            width = bitmap.getWidth();
            height = bitmap.getHeight();
        } catch (Exception e) {
            return bitmap;
        }
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, width, height);
        RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, px, px, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }


    /**
     * 获取网络图片
     *
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public static Bitmap GetImageInputStream(String imageurl) {
        URL url;
        HttpURLConnection connection = null;
        Bitmap bitmap = null;
        try {
            url = new URL(imageurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 活动图片拼接
     *
     * @param firstBitmap
     * @param secondBitmap
     * @param thirdBitmap
     * @return
     */
    public static Bitmap mergeBitmap(Bitmap firstBitmap, Bitmap secondBitmap, Bitmap thirdBitmap) {
        Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap.getHeight(), firstBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(firstBitmap, new Matrix(), null);

        int firstBitmapwidth = firstBitmap.getWidth();
        int firstBitmapHeight = firstBitmap.getHeight();
        int secondBitmapWidth = secondBitmap.getWidth();
        int secondBitmapHeight = secondBitmap.getHeight();
        int thirdBitmapWidth = thirdBitmap.getWidth();
        int thirdBitmapHeight = thirdBitmap.getHeight();

        int secondBitmapW = (firstBitmapwidth - secondBitmapWidth) / 2;
        int secondBitmapH = firstBitmapHeight - secondBitmapW - secondBitmapHeight;

        int thirdBitmapW = (firstBitmapwidth - thirdBitmapWidth) / 2;
        int thirdBitmapH = firstBitmapHeight - thirdBitmapW - thirdBitmapHeight;


        //二维码背景图
        canvas.drawBitmap(secondBitmap, secondBitmapW, secondBitmapH, null);
//二维码
        canvas.drawBitmap(thirdBitmap, thirdBitmapW, thirdBitmapH, null);

        return bitmap;
    }


    public static Bitmap mergeBitmap(Bitmap firstBitmap, Bitmap secondBitmap, Bitmap bitmapTop, String... strings) {
        Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap.getHeight(), firstBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(firstBitmap, new Matrix(), null);

        int firstBitmapwidth = firstBitmap.getWidth();
        int firstBitmapHeight = firstBitmap.getHeight();
        int secondBitmapWidth = secondBitmap.getWidth();
        int secondBitmapHeight = secondBitmap.getHeight();
        //二维码背景图
        canvas.drawBitmap(secondBitmap, (firstBitmapwidth - secondBitmapWidth) / 2, (float) (firstBitmapHeight * 0.445), null);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(56);
        paint.setTypeface(Typeface.create("黑体", Typeface.BOLD));
        paint.setColor(Color.WHITE);
        float v = paint.measureText(strings[2]);
        canvas.drawText(strings[2], firstBitmap.getWidth() / 2 - v / 2, (float) (firstBitmapHeight * 0.4), paint);

        paint.setTextSize(32);
        paint.setTypeface(Typeface.create("黑体", Typeface.NORMAL));
        float v1 = paint.measureText(strings[1]);
        float v0 = paint.measureText(strings[0]);

        canvas.drawText(strings[0], (firstBitmapwidth - v1 - v0 - 20) / 2, (float) (firstBitmapHeight * 0.425), paint);
        paint.setStrokeWidth(3);
        canvas.drawLine((firstBitmapwidth - v1 - v0 + 5) / 2 + v1, (float) (firstBitmapHeight * 0.412), (firstBitmapwidth - v1 - v0 + 5) / 2 + v1, (float) (firstBitmapHeight * 0.428), paint);
        canvas.drawText(strings[1], (firstBitmapwidth - v1 - v0 - 20) / 2 + v1 + 25, (float) (firstBitmapHeight * 0.425), paint);

//        paint.setStrokeWidth(5);
//        canvas.drawLine(firstBitmapwidth/2-15,(float) (firstBitmapHeight*0.75),firstBitmapwidth/2+1,(float) (firstBitmapHeight*0.748),paint);
//        canvas.drawLine(firstBitmapwidth/2-1,(float) (firstBitmapHeight*0.748),firstBitmapwidth/2+15,(float) (firstBitmapHeight*0.75),paint);
//        paint.setStrokeWidth(40);
//        paint.setTextSize(40);
//        String s1 = "长按识别二维码";
//        String s2 = "即可领券问诊";
//        float vs1 = paint.measureText(s1);
//        float vs2 = paint.measureText(s2);
//
//        canvas.drawText(s1,(firstBitmapwidth-vs1)/2,1040+secondBitmapHeight,paint);
//        canvas.drawText(s2,(firstBitmapwidth-vs2)/2,1090+secondBitmapHeight,paint);


        return bitmap;
    }


    /**
     * 保存方法
     */
    public static void saveBitmap(Bitmap bitmap, String savePath) {
        //  获取当前程序路径
        File f = new File(savePath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 将本地图片转成Bitmap
     *
     * @param path 已有图片的路径
     * @return
     */
    public static Bitmap openImage(String path) {
        Bitmap bitmap = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * @param context
     * @param targetFile 要保存的照片文件
     * @param path       要保存的照片的路径地址
     */
    public static void addMediaStore(Context context, File targetFile, String path) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues newValues = new ContentValues(5);
        newValues.put(MediaStore.Images.Media.DISPLAY_NAME, targetFile.getName());
        newValues.put(MediaStore.Images.Media.DATA, targetFile.getPath());
        newValues.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
        newValues.put(MediaStore.Images.Media.SIZE, targetFile.length());
        newValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, newValues);
        MediaScannerConnection.scanFile(context, new String[]{path}, null, null);//刷新相册
    }

    /**
     * base64转bitmap
     *
     * @param @param  base64String
     * @param @return 设定文件
     * @return Bitmap    返回类型
     * @throws
     * @Title: base64ToBitmap
     */
    public static Bitmap base64ToBitmap(String base64String) {
        byte[] decode = Base64.decode(base64String, Base64.NO_WRAP);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        return bitmap;
    }

    /**
     * 保存图片到相册
     */
    public static void saveImageToGallery(Context context, Bitmap mBitmap) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        // 首先保存图片
        File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "h1tx" + System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // 最后通知图库更新

        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "")));


    }

    /**
     * 给 drawable 着色
     *
     * @param drawable 需要着色的 drawable 对象
     * @param colors   ColorStateList 对象，代表需要着色的颜色
     * @return
     */
    public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
        //这里需要对 drawable 对象执行 mutate() 操作
        //该操作能防止一个屏幕里多次使用同一个图片，对其中一个图片操作时影响其他图片
        //当然，你也可以在getResource().getDrawable()的时候就执行
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable.mutate());
        DrawableCompat.setTintList(wrappedDrawable, colors);
        return wrappedDrawable;
    }

    /**
     * 将彩色图转换为纯黑白二色
     *
     * @return 返回转换好的位图
     */
    public static Bitmap convertToBlackWhite(Bitmap bmp) {
        int width = bmp.getWidth(); // 获取位图的宽
        int height = bmp.getHeight(); // 获取位图的高
        int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组

        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        int alpha = 0xFF << 24;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int grey = pixels[width * i + j];

                //分离三原色
                int red = ((grey & 0x00FF0000) >> 16);
                int green = ((grey & 0x0000FF00) >> 8);
                int blue = (grey & 0x000000FF);

                //转化成灰度像素
                grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
                grey = alpha | (grey << 16) | (grey << 8) | grey;
                pixels[width * i + j] = grey;
            }
        }
        //新建图片
        Bitmap newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        //设置图片数据
        newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

        Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, 380, 460);
        return resizeBmp;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, long maxLength, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int quality = 91;
        if (maxLength != 0) {
            bmp.compress(Bitmap.CompressFormat.JPEG, quality, output);

            while (output.toByteArray().length > maxLength) {
                quality -= 10;
                if (quality <= 0) {
                    break;
                }
                ALog.e("xkx", "max length: " + maxLength + " quality: " + quality + " output array size: " + output.toByteArray().length);
                output = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, quality, output);
            }

//            if (output.toByteArray().length > maxLength) {
//                output = new ByteArrayOutputStream();
//                bmp.compress(Bitmap.CompressFormat.JPEG, 1, output);
//            }


        } else {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, output);
        }

        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
//        58061  90262 931377
        ALog.e("bmpToByteArray bytes.length: " + result.length);
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
